import shop from "@/api/shop"
import * as types from '../mutation-type'
import {ActionContextBasic, AddToCartPayload, Product} from '@/store'

const initState = {
    all: []
};

export interface ProductsPayload {
    products: Product[]
}

export interface State {
    all: Product[]
}

const getters = {
    allProducts: (state: State) => state.all
};

const actions = {
    // 获取所有的产品数据
    getAllProducts(context: ActionContextBasic) {
        shop.getProducts((products: Product[]) => {
            const payload: ProductsPayload = {
                products
            }
            context.commit(types.RECEIVE_PRODUCTS, payload)
        })
    }
}

const mutations = {
    // 将获取到products列表更新到state中
    [types.RECEIVE_PRODUCTS](state: State, payload: ProductsPayload) {
        state.all = payload.products
    },
    // 加入购物车后，减少库存
    [types.DECREMENT_PRODUCT_INVENTORY](state: State, payload: AddToCartPayload) {
        const product = state.all.find(item => item.id === payload.id);
        if (product) {
            product.inventory--
        }
    }
};

export default {
    state: initState,
    getters,
    actions,
    mutations

}
